import { bindPermission, deleteRole, insertOneRole, lookRole, lookAllRole, unbindPermission, updateOneRole } from '@/api/role'

import store from '@/store/index'

const getDefaultState = () => {
  return { roleList: [] }
}

const state = getDefaultState()

const mutations = {
  SET_LIST: (state, value) => {
    state.roleList = value
  },
}

const actions = {
  // 条件查询
  async lookRoleAll({ commit, state }) {
    // 缓存
    if (state.roleList.length > 0) {
      resolve(state.roleList)
      return
    }
    return new Promise((resolve, reject) => {
      lookRole()
        .then((response) => {
          commit('SET_LIST', response.data)
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 条件查询
  async lookRole({ state }, role) {
    return new Promise((resolve, reject) => {
      lookAllRole(role)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 添加一条角色
  async insertOneRole({ commit, state }, role) {
    return new Promise((resolve, reject) => {
      insertOneRole(role)
        .then((response) => {
          store.dispatch('role/resetList')
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 修改角色
  async updateOneRole({ commit, state }, role) {
    return new Promise((resolve, reject) => {
      updateOneRole(role)
        .then((response) => {
          store.dispatch('role/resetList')
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 批量删除角色
  async deleteRoles({ commit, state }, ids) {
    store.dispatch('role/resetList')
    return new Promise((resolve, reject) => {
      deleteRole(ids)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 绑定权限到角色
  async bindPermission({ state }, map) {
    return new Promise((resolve, reject) => {
      bindPermission(map)
        .then((response) => {
          resolve(response)
          store.dispatch('user/getInfo')
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 解绑权限到角色
  async unbindPermission({ state }, map) {
    return new Promise((resolve, reject) => {
      unbindPermission(map)
        .then((response) => {
          resolve(response)
          store.dispatch('user/getInfo')
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 重置列表
  async resetList({ commit, state }) {
    // 置空
    if (state.routerList.length > 0) {
      commit('SET_LIST', [])
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
